<?php

namespace App\Service;

use App\Constants\ErrorCode;
use App\Exception\BusinessException;
use App\Library\Common;
use App\Model\DadaShop;
use App\Model\data\CurrentShopData;
use App\Model\DeliverySendOrder;
use App\Model\DeliverySendOrderLog;
use App\Model\FlyOrder;
use App\Model\FlyShopBalance;
use App\Model\FlyShopDadaOrder;
use App\Model\PollLog;
use App\Model\ShopSendAddress;
use Hyperf\DbConnection\Db;
use Hyperf\Snowflake\IdGeneratorInterface;
use Hyperf\Utils\ApplicationContext;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\ContainerInterface;
use Hyperf\Di\Annotation\Inject;
use Psr\Container\NotFoundExceptionInterface;
use Swoole\Exception;

//use function Symfony\Component\Translation\t;

class DadaService extends BaseService
{
    const ORDER_ADD_URL = "/api/order/addOrder";//直接下单
    const ORDER_PRICE = "/api/order/queryDeliverFee";//询价
    const ORDER_AFTER_PRICE = "/api/order/addAfterQuery";//询价后下单
    const ORDER_INFO = "/api/order/status/query";//询价后下单
    const SHOP_ADD_URL = "/api/shop/add";//开通门店
    const SHOP_EDIT_URL = "/api/shop/update";//开通门店

    const CITY_ORDER_URL = "/api/cityCode/list";//开通城市列表
    const ORDER_CANCEL = "/api/order/formalCancel";//取消订单
    const LINE_URL = "https://newopen.imdada.cn";//正式环境
    const TEST_URL = "http://newopen.qa.imdada.cn";//测试环境


    const  CANCEL_ID = [
        '1'	=>'没有配送员接单',
        '2'	=>'配送员没来取货',
        '3'	=>'配送员态度太差',
        '4'	=>'顾客取消订单',
        '5'	=>'订单填写错误',
        '34'	=>'配送员让我取消此单',
        '35'	=>'配送员不愿上门取货',
        '36'	=>'我不需要配送了',
        '37'	=>'配送员以各种理由表示无法完成订单',
        '10000'	=>'其他',
        ];
    const  DADA_STATUS = [
        '1'	=>'待接单',
        '2'	=>'待取货',
        '3'	=>'配送中',
        '4'	=>'已完成',
        '5'	=>'已取消',
        '8'	=>'指派单',
        '9'	=>'妥投异常之物品返回中',
        '10'	=>'妥投异常之物品返回完成',
        '100'	=>'骑士到店',
        '1000'	=>'创建达达运单失败',
    ];

    protected $key;   // 账户key
    protected $secret;  // 账户secret
    protected $source_id;  // 账户secret
    protected $config;  // 账户secret
    protected $host;  // 环境
//    protected $source_id;  // 商户id
    public $type = 'dada';  // 默认快递100

    /**
     * @Inject
     * @var DeliverySendService
     */
    private $delivery;


    /**
     * @param $param
     * @param int $dada_order_id
     * @return array|bool
     */
    public function cancel_order($param,$dada_order_id=0){

        $dada_data = $this->get_sign($param,2);
        $url = $this->get_dada_config('host').self::ORDER_CANCEL;
        $res = Common::request_by_curl($url,json_encode($dada_data));
        $res = json_decode($res,true);
        if($res['status']=='success'){
            Db::beginTransaction();
            try {
                $res2 = $this->delivery->cancel_order_info($param['order_id'],$res['result']['deduct_fee'],$param);
                if($res2){
                    $this->cancelDadaOrder(intval($param['id']),intval($dada_order_id),$param['cancel_reason'],floatval($res['result']['deduct_fee']));
                    Db::commit();
                    return  true;
                }else{
                    Db::rollBack();
                    return  false;
                }
            }catch (Exception $exception){
                Db::rollBack();
                return  false;
            }
        }
        return $res;
    }


    /**
     * @param $order_id
     * @return array
     */
    public function order_info($order_sn)
    {
        $ticket = 'info_'.$order_sn;
        $redis_info = $this->redis_get($ticket);
        if($redis_info){
            return $redis_info;
        }else{
            $dada_data = $this->get_sign(['order_id'=>$order_sn],2);
            $url = $this->get_dada_config('host').self::ORDER_INFO;
            $res = Common::request_by_curl($url,json_encode($dada_data));
            $res = json_decode($res,true);
            if($res['status']=='success'){
                $this->redis_set($ticket,$res['result']);
                $this->delivery->add_log($res['result']);
            }
            return $res;
        }

    }
    public function get_city_list(){

        $ticket_index = "dada_city_list";
//        $json_redis = $this->redis_get($ticket_index);
////        已存储的直接返回
//        if(!$json_redis){
//            return $json_redis;
//        }else{
            $dada_data =  $this->get_sign('',2);
            $url = self::LINE_URL.self::CITY_ORDER_URL;
            $res = Common::request_by_curl($url,json_encode($dada_data));
            $res = json_decode($res,true);
//            查询成功的，缓存一天
            if($res&&isset($res['status'])&&$res['status']=='success'){
                $this->redis_set($ticket_index, $res['result'],3600*24*30);
                return $res['result'];
            }else{
                return $res;
            }

//        }
    }
    public function get_city_code($address = ''){
            $url = "https://restapi.amap.com/v3/geocode/geo?address=".$address."&output=JSON&key=".$this->get_dada_config('gd_key');
            $res = json_decode(Common::getUrl($url),true);
            if($res['status']==1){
                return $res['geocodes']['0']['citycode'];
            }else{
                var_dump('地理标识逆向失败原因：');
                var_dump($res);
                return 0;
            }
    }

    /**
     * @param string $address
     * @return int
     */
    public function check_city($address){
        $ticket_index = "city_code-".$address;
        $json_redis = $this->redis_get($ticket_index);
    //        已存储的直接返回
//        if($json_redis){
//            return $json_redis;
//        }else{
            $city_code =  $this->get_city_code($address);
            $city_list =  $this->get_city_list();
            $city_code_list =  array_column($city_list,'cityCode');
            $arr = ['city_code'=>$city_code, 'address'=>$address];
            if(in_array($city_code,$city_code_list)){
                $arr['is_usable']= 1;
                $this->redis_set($ticket_index,$arr,3600*24*30);
                return $arr;
            }else{
                $arr['is_usable']= 0;
                $this->redis_set($ticket_index,$arr,3600*24*30);
                return $arr;
            }
//        }

    }
    /**
     *获取配置
     * @param string $name
     * @return string
     */
    public function get_dada_config($name)
    {
        $arr = ['host','source_id'];
        if(in_array($name,$arr)){
            $host_type=   config('dada.' . $this->type.'.host_type');
            if($host_type==1){
                if($name=='source_id'){
                    return  config('dada.' . $this->type.'.'.$name);
                }
                if($name=='host'){
                    return self::LINE_URL;
                }
            }else{
                if($name=='source_id'){
                    return  "355423250";
                }
                if($name=='host'){
                    return self::TEST_URL;
                }
            }
        }else{
            return config('dada.' . $this->type.'.'.$name);
            return '';
        }

    }


    public function check_shop(int $shop_id)
    {
        $station = DadaShop::query()->where('origin_shop_id',$shop_id)->first();
        if($station){
            return true;
        }else{
            return false;
        }
    }

    /**
     * 获取门店详情
     * @param int $shop_id
     * @return \Hyperf\Database\Model\Builder|\Hyperf\Database\Model\Model|object|null
     */
    public function get_station(int $shop_id)
    {
//        $config = $this->get_dada_config();
//        var_dump($config);
        return  DadaShop::query()->where('origin_shop_id',$shop_id)->first();
    }

    /**
     * 下单
     * @param array $param
     * @param array $order_info
     * @param int $user_id
     * @return int
     */
    public function   insert_order(array $param,$order_info,$user_id=0){

        $price_redis =  $this->redis_get('dada_price-'.$param['origin_id']);
        if(!$price_redis){
            throw new \RuntimeException("询价超时,请稍后重新询价", ErrorCode::SERVER_ERROR);
        }
        $shop_info = CurrentShopData::getData();
        //询价时，
//        var_dump($price_redis);die;
        $address =ShopSendAddress::query()->where('id','2')->first()->toArray();
        $send_order  = [
            'service_type'=>2,
            'delivery_type'=>'dada',
            'delivery_name'=>'达达配送',
            'type'=>2,
            'is_poll'=>1,
            'delivery_fee'=>$price_redis['deliverFee'],
            'delivery_order_id'=>$price_redis['deliveryNo'],
            'order_id'=>$order_info['order_id'],
            'order_sn'=>$order_info['order_sn'],
            'task_id'=>'0',
            'created_at'=>date('Y-m-d H:i:s'),
            'from_address'=>$address['street_str'],
            'from_name'=>$address['link_name'],
            'from_phone'=>$address['phone'],
            'to_address'=>$param['receiver_address'],
            'to_name'=>$param['receiver_name'],
            'to_phone'=>$param['receiver_phone'],
            'send_date'=> date('Y-m-d H:i:s'),
            'start_time'=> $param['start_time']??'08:00',
            'end_time'=> $param['end_time']??'18:00',
            'order_status'=> 1,
        ];
        $send_order['created_at'] = $param['created_at'] = date('Y-m-d H:i:s');
        $send_order['create_by']  = $param['create_by'] = $user_id;
        $send_id =  DeliverySendOrder::query()->insertGetId(Common::filter_null($send_order));
//        物流发货单👆

//        订阅单👇
        $poll_data  = [
            'order_sn'=>$order_info['order_sn'],
            'order_type'=>1,
            'send_type'=>2,
            'com'=>'dada',
            'num'=>$price_redis['deliveryNo'],
            'created_at'=>date('Y-m-d H:i:s'),
            'order_status'=> 1,
            'delivery_fee'=>$price_redis['deliverFee'],
        ];
        $poll_id =  PollLog::query()->insertGetId($poll_data);

        //订单发货单👇
        $shop_delivery_data  = [
            'order_sn'=>$order_info['order_sn'],
            'order_id'=>$order_info['order_id'],
            'send_type'=>1,
            'delivery_type'=>2,
            'com'=>'dada',
            'logistics_sn'=>$price_redis['deliveryNo'],
            'logistics_name'=>'达达配送',
            'create_time'=>time(),
            'send_time'=>time(),
            'poll_id'=>$poll_id,
            'shop_id'=> $shop_info->id,
        ];
        //        更新余额
//        $FlyShopBalance = New FlyShopBalance();
//        $FlyShopBalance->where(['shop_id'=>$shop_info->id,'platform'=>1])->decrement('balance',$price_redis['deliverFee']);
//        $FlyShopBalance->where(['shop_id'=>$shop_info->id,'platform'=>1])->increment('total_consumer',$price_redis['deliverFee']);
        $orderInstance = make(FlyShopDadaOrder::class);
        $orderInstance->shop_id = $shop_info->id;
        $orderInstance->pay_price = $amount;
        $orderInstance->paid_price = $amount;
        $orderInstance->pay_time = time();
        $orderInstance->order_sn = $this->generateSn("DDXF");
        $orderInstance->pay_outer_sn = '-';
        $orderInstance->create_time = time();
        $orderInstance->order_status = 2;
        $orderInstance->order_id = $order_info['order_id'];
        if (!$orderInstance->save()) {
            return false;
        }

        FlyShopDadaOrder::query()->insert([
            'shop_id'=>$shop_info->id,
            'order_sn'=>$order_info['order_id'],
            'type'=>2,
        ]);
//        fly_shop_dada_order
        $this->createDadaOrder(intval($shop_info->id),intval($order_info['order_id']),'',intval($shop_info->id),3,1,0,intval($poll_id));
        //发货单id
        $this->delivery->sendDelivery(intval($order_info['order_id']),intval($shop_info->id),3,1,0,intval($poll_id));
        return true;
    }

    /**
     * 插入门店记录
     * @param array $param
     * @param int $user_id
     * @return int
     */
    public function   insert_station(array $param,$user_id=0){
        $param['created_at'] = date('Y-m-d H:i:s');
        $param['create_by'] = strval($user_id);
        $param['lng'] = strval($param['lng']);
        $param['business'] = strval($param['business']);
        $param['lat'] = strval($param['lat']);
        $station_id = DadaShop::query()->insertGetId(Common::filter_null($param));
        return  $station_id;
    }

    /**
     * 下单
     * @param array $param
     * @param int $user_id
     * @return mixed
     */
    public function   add_order(array $param,$user_id=0){
        $dada_data = $this->get_sign($param,2);
        $url = self::TEST_URL.self::ORDER_ADD_URL;
        $result   = Common::request_by_curl($url,json_encode($dada_data));
        return json_decode($result,true);
    }

    /**
     * 预下单询价
     * @param array $param
     * @param int $user_id
     * @return mixed
     */
    public function   check_price(array $param,$user_id=0){
        $redis_price = $this->redis_get('dada_price-'.$param['origin_id']);
        if($redis_price){
            return [
                "status"=>"success",
                "result"=>$redis_price,
            ];
        }else{
//            没有的时候
//            清空旧数据
            $this->delivery->delete_order($param['origin_id'],2);
            $dada_data = $this->get_sign($param,2);
            $url = $this->get_dada_config('host').self::ORDER_PRICE;
            $result   = Common::request_by_curl($url,json_encode($dada_data));
            $result = json_decode($result,true);
            if($result['status']=='success'){
                $result['result']['origin_id'] = $param['origin_id'];
                $this->redis_set('dada_price-'.$param['origin_id'],$result['result'],170);
            }
            return $result;
        }

    }

    /**
     * 预下单询价后下单
     * @param array $param
     * @param int $user_id
     * @return mixed
     */
    public function   after_price_add(array $param,$user_id=0){
            $dada_data = $this->get_sign($param,2);
            $url = $this->get_dada_config('host').self::ORDER_AFTER_PRICE;
            $result   = Common::request_by_curl($url,json_encode($dada_data));
            return json_decode($result,true);
    }

    /**
     * 整合签名和参数
     * @param $param
     * @param int $type
     * @return array
     */
    public function   get_sign($param,$type=1){

        if ($param){
            if($type==1){
                $body = json_encode(array($param));
            }else{
                $body = json_encode($param);
            }
        }else{
            $body = '';
        }


        $dada_data = [
            "app_key"=> strval(config('dada.' . $this->type.'.app_key')),
            "timestamp"=>strval(time()),
//            "timestamp"=>"1656498755",
            "format"=>"json",
            "v"=>"1.0",
            "source_id"=> $this->get_dada_config('source_id'),
//            "source_id"=>"355423250",
            "body"=>$body,
        ];

//        排序
        ksort($dada_data);
//        拼接后首尾增加secret
        $str = '';
        foreach ($dada_data as $key=>$value){
            $str.=$key.$value;
        }
        $str  =  $this->get_dada_config('app_secret').$str.$this->get_dada_config('app_secret');
//        MD5大写
        $sign = strtoupper(md5($str));
        $dada_data['signature'] = $sign;
        return $dada_data;

    }

    /**
     * 开通门店
     * @param array $param
     * @return bool|mixed
     */
    public function   open_station(array $param){
        $dada_data = $this->get_sign($param);
        $url = $this->get_dada_config('host').self::SHOP_ADD_URL;
        $result   = Common::request_by_curl($url,json_encode($dada_data));
        return json_decode($result,true);
    }
    /**
     * 修改门店
     * @param array $param
     * @return bool|mixed
     */
    public function   edit_station(array $param){
        $id = $param['id'];
        unset($param['id']);
        $dada_data = $this->get_sign($param,2);
        $url = $this->get_dada_config('host').self::SHOP_EDIT_URL;
        $result = Common::request_by_curl($url,json_encode($dada_data));
        $result =  json_decode($result,true);
        if($result['status']=='success'){
            $param['status']=1;
           DadaShop::query()->where('origin_shop_id',$param['origin_shop_id'])->update($param);
        }
        return $result;

    }


    /**
     * 校验签名
     * @param array $param
     * @return bool
     */
    public function check_sign(array $param)
    {
       $sign_arr = [$param['update_time'],$param['client_id'],$param['order_id']];
        sort($sign_arr);
        $sign_arr = Common::filter_null($sign_arr);
       $str = implode('',$sign_arr);
       $sign = md5($str);
       var_dump($sign);
       var_dump($param['signature']);
       if($param['signature']==$sign){
           return true;
       }else{
           return false;
       }
    }

    /**
     * 回调操作
     * @param array $param
     */
    public function call_back(array $param)
    {
        $order_status = $param['order_status'];
        Db::beginTransaction();
        $order_info =  FlyOrder::query()->where('order_sn',$param['order_id'])->first();
        try{
            $log_data = [
                'time'=>date('Y-m-d H:i:s'),
                'order_sn'=>$order_info->order_sn,
                'com'=>'dada',
                'num'=>$param['client_id'],
                'order_id'=>$order_info->order_id,
                'status_code'=>$order_status,
                'status'=>self::DADA_STATUS[$order_status],
                'json_data'=>json_encode($param),
            ];
            if(DeliverySendOrderLog::query()->insert($log_data)){
                $send_edit = [
                    'order_status'=>$order_status,
                    'cancel_reason'=>$param['cancel_reason'],
                    'cancel_from'=>$param['cancel_from'],
                ];
                switch ($order_status ) {
                    case 4;
//            配送完成
//                todo  1订单完成 2 运单作废  3运单日志作废
                        $order_info->order_status= 3;
                        $order_info->save();
                        break;
                    case 5;
//            取消
//                todo  1订单取消delivery_id  2 运单作废  3运单日志作废
                        $order_info->delivery_id= 0;
                        $order_info->save();
                        $this->delivery->cancel_order_info($param['order_id']);
                        $send_edit['state']=2;
                        break;
                    case 10000;
//            创建运单失败
//                todo  1订单取消delivery_id  2 运单作废  3运单日志作废
                        $order_info->delivery_id= 0;
                        $order_info->save();
                        $send_edit['state']=2;
                        $this->delivery->cancel_order_info($param['order_id']);
                        break;
                    default:
//                todo  更新物流信息
                        break;
                }
                PollLog::query()->where('order_sn',$param['order_id'])->update($send_edit);
                DeliverySendOrder::query()->where('order_sn',$param['order_id'])->update($send_edit);
                Db::commit();
                return true;
            }else{
                return false;
            }
        }catch (\Exception $e){
            Db::rollBack();
            var_dump($e->getMessage());
            return false;
        }
    }

    /**
     * 生成达达下单消费订单
     * @param int $shop_id
     * @param array $order_info
     * @param float $amount
     * @param int $num
     * @param string $com
     * @return bool
     */
    public function createDadaPayOrder(int $shop_id, array $order_info, float $amount,$num=0,$com='dada'): bool
    {
        if (!$this->check_shop($shop_id)) {
            return false;
        }
        // 扣费金额不低于余额
        $shop_balance = make(FlyShopBalance::class)
            ->where('shop_id', '=', $shop_id)
            ->where('platform', '=', 1)// 达达平台
            ->first();
        if (empty($shop_balance)) {
            return false;
        }
        $balance = Common::yuan2fen((float)$shop_balance->balance) - Common::yuan2fen($amount);
        if ($balance < 0) {// 账户余额不足以扣款
            return false;
        }
        $shop_balance->balance = Common::fen2yuan($balance);
        $shop_balance->total_consumer =  Common::fen2yuan(Common::yuan2fen((float)$shop_balance->total_consumer) + Common::yuan2fen($amount));
        if (!$shop_balance->save()) {
            return false;
        }
        $orderInstance = make(FlyShopDadaOrder::class);
        $orderInstance->shop_id = $shop_id;
        $orderInstance->pay_price = $amount;
        $orderInstance->paid_price = $amount;
        $orderInstance->pay_time = time();
        $orderInstance->order_sn = $order_info['order_sn'];
        $orderInstance->create_time = time();
        $orderInstance->order_status = 2;
        $orderInstance->order_id = $order_info['order_id'];
        $orderInstance->type = 2;
        $orderInstance->com = $com;
        $orderInstance->num = $num;
        if (!$orderInstance->save()) {
            return false;
        }
        return true;
    }
    /**
     * 生成达达配送订单
     * @param int $shop_id
     * @param string $outer_sn
     * @param int $order_id
     * @param float $amount
     * @return bool
     */
    public function createDadaOrder(int $shop_id, int $order_id, string $outer_sn, float $amount): bool
    {
        if (!$this->check_shop($shop_id)) {
            return false;
        }
        // 扣费金额不低于余额
        $shop_balance = make(FlyShopBalance::class)
            ->where('shop_id', '=', $shop_id)
            ->where('platform', '=', 1)// 达达平台
            ->first();
        if (empty($shop_balance)) {
            return false;
        }
        $balance = Common::yuan2fen((float)$shop_balance->balance) - Common::yuan2fen($amount);
        if ($balance < 0) {// 账户余额不足以扣款
            return false;
        }
        $shop_balance->balance = Common::fen2yuan($balance);
        if (!$shop_balance->save()) {
            return false;
        }

        $orderInstance = make(FlyShopDadaOrder::class);
        $orderInstance->shop_id = $shop_id;
        $orderInstance->pay_price = $amount;
        $orderInstance->paid_price = $amount;
        $orderInstance->pay_time = time();
        $orderInstance->order_sn = $this->generateSn("DDXF");
        $orderInstance->pay_outer_sn = $outer_sn;
        $orderInstance->create_time = time();
        $orderInstance->order_status = 2;
        $orderInstance->order_id = $order_id;
        if (!$orderInstance->save()) {
            return false;
        }

        return true;
    }

    /**
     * 取消达达配送订单
     * @param int $shop_id
     * @param int $dada_order_id
     * @param string $reason
     * @param float $refund_price
     * @return bool
     */
    public function cancelDadaOrder(int $shop_id, int $dada_order_id, string $reason, float $refund_price): bool
    {
        $order_instance = make(FlyShopDadaOrder::class)
            ->where('shop_id', '=', $shop_id)
            ->where('id', '=', $dada_order_id)
            ->first();
        if ($order_instance->order_status != 2) {
            return false;
        }

        // 更新订单账户余额
        $shop_balance = make(FlyShopBalance::class)
            ->where('shop_id', '=', $order_instance->shop_id)
            ->where('platform', '=', 1)// 达达平台
            ->first();
        if (empty($shop_balance)) {
            return false;
        }
        $balance = Common::yuan2fen((float)$shop_balance->balance) + Common::yuan2fen($refund_price);
        if ($balance < 0) {// 账户余额不足以扣款
            return false;
        }

        $order_instance->order_status = 3;
        $order_instance->refund_price = $refund_price;
        $order_instance->close_reason = $reason;
        if (!$order_instance->save()) {
            return false;
        }

        $shop_balance->balance = Common::fen2yuan($balance);
        if (!$shop_balance->save()) {
            return false;
        }
        return true;
    }

    /**
     * 生成达达充值订单
     * @param int $shop_id
     * @param int $amount
     * @return string
     */
    public function rechargeCreate(int $shop_id, int $amount): string
    {
        $order_instance = make(FlyShopDadaOrder::class);
        $order_instance->shop_id = $shop_id;
        $order_instance->pay_price = $amount;
        $order_instance->order_status = 1;
        $order_instance->order_sn = $this->generateSn();
        $order_instance->type = 1;// 1充值订单 2消费订单
        if (!$order_instance->save()) {
            return "";
        }
        return $order_instance->order_sn;
    }

    /**
     * 生成达达单号
     * @param string $prefix
     * @return string
     */
    public function generateSn($prefix = 'DDCZ'): string
    {
        try {
            $generator = ApplicationContext::getContainer()->get(IdGeneratorInterface::class);
            $id = $generator->generate();
        } catch (NotFoundExceptionInterface $e) {
            echo $e->getMessage();
            throw new BusinessException(ErrorCode::NORMAL_ERROR);
        } catch (ContainerExceptionInterface $e) {
            echo $e->getMessage();
            throw new BusinessException(ErrorCode::NORMAL_ERROR);
        } catch (\Throwable $exception) {
            echo $exception->getMessage();
            throw new BusinessException(ErrorCode::NORMAL_ERROR);
        }
        return $prefix . "" . date("Ym") . substr(strval($id), 8) . rand(10000000, 99999999);
    }

    /**
     * 根据单号获取订单记录
     * @param string $order_sn
     * @return array
     */
    public function getDadaWaitPayOrderBySn(string $order_sn): array
    {
        $order = make(FlyShopDadaOrder::class)
            ->where(['order_sn' => $order_sn, 'order_status' => 1, 'type' => 1])
            ->first();
        return empty($order) ? [] : $order->toArray();
    }

    /**
     * 达达充值回调支付
     * @param string $order_sn
     * @param string $pay_type
     * @param string $pay_method
     * @param string $pay_outer_sn
     * @return bool
     */
    public function payNotify(string $order_sn, string $pay_type, string $pay_method, string $pay_outer_sn): bool
    {
        $order_instance = make(FlyShopDadaOrder::class)
            ->where('type', '=', 1)
            ->where('order_sn', '=', $order_sn)
            ->first();
        if (empty($order_instance)) {
            return false;
        }
        $order_instance->is_pay = 1;
        $order_instance->pay_time = time();
        $order_instance->pay_type = $pay_type;
        $order_instance->pay_method = $pay_method;
        $order_instance->paid_price = Db::raw('pay_price');
        $order_instance->pay_outer_sn = $pay_outer_sn;
        if (!$order_instance->save()) {
            return false;
        }
        // 更新订单账户余额
        $shop_balance = make(FlyShopBalance::class)
            ->where('shop_id', '=', $order_instance->shop_id)
            ->where('platform', '=', 1)// 达达平台
            ->first();
        if (empty($shop_balance)) {
            return false;
        }
        $balance = Common::yuan2fen((float)$shop_balance->balance) + Common::yuan2fen((float)$order_instance->pay_price);
        $shop_balance->balance = Common::fen2yuan($balance);
        if (!$shop_balance->save()) {
            return false;
        }
        return true;
    }

    /**
     *  查询商铺门店达达余额，对比，达达单价，
     * @param $need
     * @param $shop_id
     * @return int
     */
    public function check_balance($need,$shop_id)
    {
//        todo
//        查询商铺门店达达余额，对比，达达单价，
        $shop_info = CurrentShopData::getData();
        $shop_balance = FlyShopBalance::query()->where(['platform'=>1,'shop_id'=>$shop_info->id])->first();
        $balance = 0;
        if($shop_balance){
            $balance =  $shop_balance->balance;
        }
        if($balance>=$need){
            return  true;
        }else{
            return false;
        }
    }

}